// --------------------------------------------------------------------------------------------------------------------
// <copyright file="EnsureWritableBulbItem.cs" company="StyleCop for ReSharper Development Team">
//   Copyright (c) StyleCop for ReSharper Development Team. All rights reserved.
// </copyright>
// <summary>
//   Defines the EnsureWritableBulbItem type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace StyleCop.For.ReSharper.BulbItems.Framework
{
    #region Using Directives

    using JetBrains.Application;
    using JetBrains.ProjectModel;
    using JetBrains.TextControl;
    using JetBrains.Util;

    #endregion

    /// <summary>
    /// Executes the QuickFix within a Command Context.
    /// </summary>
    public abstract class EnsureWritableBulbItem : BulbItemBase
    {
        #region Public Methods

        /// <summary>
        /// Ensures that the current document is writeable.
        /// </summary>
        /// <param name="solution">
        /// Current Solution.
        /// </param>
        /// <param name="textControl">
        /// Current Text Control to modify.
        /// </param>
        public override void Execute(ISolution solution, ITextControl textControl)
        {
            using (CommandCookie.Create(this.Text))
            {
                this.ExecuteEnsureWritable(solution, textControl);
            }
        }

        /// <summary>
        /// Ensures that the file the QuickFix is being performed on is writable.
        /// </summary>
        /// <param name="solution">
        /// Current Solution.
        /// </param>
        /// <param name="textControl">
        /// Current Text Control to modify.
        /// </param>
        public virtual void ExecuteEnsureWritable(ISolution solution, ITextControl textControl)
        {
            using (var modificationCookie = textControl.Document.EnsureWritable())
            {
                if (modificationCookie.EnsureWritableResult == EnsureWritableResult.SUCCESS)
                {
                    this.ExecuteInner(solution, textControl);
                }
            }
        }

        /// <summary>
        /// Performs the QuickFix, inserts the configured modifier into the location specified by
        /// the violation.
        /// </summary>
        /// <param name="solution">
        /// Current Solution.
        /// </param>
        /// <param name="textControl">
        /// Current Text Control to modify.
        /// </param>
        public abstract void ExecuteInner(ISolution solution, ITextControl textControl);

        #endregion
    }
}